import { lazy, useRef, useState, useEffect } from 'react'
/* -------------------------------------------------------- Declare -- */
const { $lazy, $fn, $http, $ } = window
import { dataTypeData, keyData } from './_utils/back-data'
import { formTypeData } from './_utils/front-data'
import CopyFront from '../_config/copy-front'
import CopyBack from '../_config/copy-back'
import PreTableTemplate from './_config/pre-table-template'
import CreateTempFile from '../_config/create-temp-file'
import { getTemplateData, getFrontData, getBackData } from '../_utils/tool'
/* -------------------------------------------------------- Async Component -- */
const SubmitForm = $lazy.hook(()=>import('#cpt/form/submit-form'))
const Page = lazy(()=>import('#tp/content/page-content'))
const TableEdit= lazy(()=>import('./_config/table-edit'))
/* -------------------------------------------------------- ata -- */
const _cols = [
	{ label: 'id', name: 'id', data_type: 'unsigned()', not_null:1, auto_increment:1, key:'primary_key()' },
	{ label: '启用', name: 'enabled', data_type: 'tiny_unsigned()', def: 0, form_type:'radio'},
	{ label: '备注', name: 'mark', data_type: 'string_len', len:30, form_type:'textarea'},
	{ label: '创建人', name: 'create_user', data_type: 'unsigned()', not_null:1 },
	{ label: '修改人', name: 'update_user', data_type: 'unsigned()'},
	{ label: '创建时间', name: 'create_time', data_type: 'timestamp()', def:'Expr::current_timestamp()'},
	{ label: '修改时间', name: 'update_time', data_type: 'timestamp()', def:'Expr::current_timestamp()', extra:'on update current_timestamp'}
]
const _cols0 = [
	{ label: 'id', name: 'id', data_type: 'integer()', not_null:1, auto_increment:1, key:'primary_key()' },
	{ label: '启用', name: 'enabled', data_type: 'tiny_unsigned()', def: 0, form_type:'radio'},
	{ label: '备注', name: 'mark', data_type: 'string_len', len:30, form_type:'textarea'},
	{ label: '创建人', name: 'create_user', data_type: 'integer()', not_null:1 },
	{ label: '修改人', name: 'update_user', data_type: 'integer()'},
	{ label: '创建时间', name: 'create_time', data_type: 'timestamp()', def:'Expr::current_timestamp()'},
	{ label: '修改时间', name: 'update_time', data_type: 'timestamp()', def:'Expr::current_timestamp()', extra:'on update current_timestamp'}
]
const _cols1 = [
	{ label: 'id', name: 'id', data_type: 'unsigned()', not_null:1, auto_increment:1, key:'primary_key()'},
	{ label: '名称', name: 'label', data_type: 'string_len', len:5, not_null:1, key:'unique_key()'},
	{ label: '值', name: 'value', data_type: 'char_len', len:2, not_null:1, key:'unique_key()'},
	{ label: '启用', name: 'enabled', data_type: 'tiny_unsigned()', def: 1 },
	{ label: '创建人', name: 'create_user', data_type: 'unsigned()', not_null:1 },
	{ label: '修改人', name: 'update_user', data_type: 'unsigned()'},
	{ label: '创建时间', name: 'create_time', data_type: 'timestamp()', def:'Expr::current_timestamp()'},
	{ label: '修改时间', name: 'update_time', data_type: 'timestamp()', def:'Expr::current_timestamp()', extra:'on update current_timestamp'}
]
/* -------------------------------------------------------- Page Component -- */
const Index = () => {
	const formRef = useRef()
	const [info, setInfo] = useState({ title:'', database:'', folder:'' })
	const [template, setTemplate] = useState()
	const [ key, setKey ] = useState(0)
	const [ ajax, setAjax ] = useState({ loading:false })
	const colsRef = useRef($fn.local('temp-cols') || _cols )
	useEffect(()=>{
		$http.pull(null, 'project/info', { loading:true }).then( d => {
			if(d) setInfo(d)
		} )
		$http.pull(null, 'template/table', { loading:true }).then( d => {
			setTemplate(d.content)
		} )
	},[])
	const cols = [
		{ title: '标签/注释', dataIndex: 'label', width:100 },
		{ title: '字段名', dataIndex: 'name', width: 110 },
		{ title: '数据类型', dataIndex: 'data_type', type:'select', group:1, data: dataTypeData, width:280, el:{listHeight:500} },
		{ title: '数据长度', dataIndex: 'len', mode:'number', width:70 },
		{ title: '是否为空', dataIndex: 'not_null', type:'switch', width:60, align:'center' },
		{ title: '自动增长', dataIndex: 'auto_increment', type:'switch', width:60, align:'center' },
		{ title: '主键', dataIndex: 'key', type:'select', data:keyData, width:120 },
		{ title: '默认值', dataIndex: 'def', width:80 },
		// { title: '检查约束', dataIndex: 'check', p: 'Expr::col( My::Id).eq(1)', width:100 },
		{ title: '额外参数', dataIndex: 'extra', width:100 },
		{ title: '表单类型', dataIndex: 'form_type', type:'select', data: formTypeData, width:150 },
		{ title: '必填', dataIndex: 'r', type:'switch', width:60, align:'center' },
		{ title: 'half', dataIndex: 'half', type:'switch', width:60, align:'center' },
	]
	const config = { 
		formRef,
		loading: ajax.loading,
		api 		: 'file/create_table',
		labelWidth 	: 's2',
		param 		: { cols:colsRef.current, table_name: $fn.local('temp-name') || '',table_comment: $fn.local('temp-comment') || ''  },
		setParam 	: ({ table_name }) =>({ table_name: table_name.includes('-') ? table_name.replace(/-/g,'_') : table_name }),
		data: [
			{ label:'表名',  name:'table_name', r:1, change:({value}) => $fn.local('temp-name', value) },
			{ label:'表注释',  name:'table_comment', change:({value}) => $fn.local('temp-comment', value) },
			{ label:'表模板',  name:'temp', type:'select', api:'template/dict_migration', change:({value, ref, row}) => {
				$fn.getRow(config,'cols').hide = !!value
				ref.setValue({ table_name: row?.name_en ?? '', table_comment: row.label })
				ref.update()
			} },
			{ label:'字段',  name:'cols', r:1, slot: v => <TableEdit {...v} p group cols={cols} onChange={value=> $fn.local('temp-cols', value) }/>},
		],
		controls: {
			ok: { label: '生成建表文件' },
			before: [
				{ label:'常用 i32', ghost:1, click: () => {
					$fn.localRemove('temp-cols')
					colsRef.current = _cols0
					setKey(k => k + 1)
				}},
				{ label:'常用 u32', ghost:1, click: () => {
					$fn.localRemove('temp-cols')
					colsRef.current = _cols
					setKey(k => k + 1)
				}},
				{ label:'字典', ghost:1, click: () => {
					$fn.localRemove('temp-cols')
					colsRef.current = _cols1
					setKey(k => k + 1)
				}},
				{ label:'生成模板', click: () => CreateTempFile({ data:$.ref(formRef).getValue(), folder: info.folder, folder_front: info.folder_front })},
				{ label:'复制前端', ghost:1, click: () => CopyFront( getFrontData(window.$.ref(formRef).getValue()) ) },
				{ label:'复制后端', ghost:1, click: () => CopyBack( getBackData(window.$.ref(formRef).getValue()) ) },
				{ label:'预览表', ghost:1, click: () => PreTableTemplate({ formRef, template, folder: info.folder })},
			]
		},
		onSubmit: ({ api, param:{ table_name, table_comment, temp, cols } }) => {
			$fn.confirm({ msg: `确认生成表【${table_name}】？`, onOk: ()=>{
				const _template = temp ? temp : getTemplateData( { table_name, table_comment, template, cols } )
				$http.post(setAjax, api, { param: { folder: info.folder, table_name, template: _template  }  }).then(()=>{
					$fn.msg.success(`表【${table_name}】生成成功`)
				})
			} })
		}
	} // eslint-disable-line
	const page = {
		title: '建表 - ' + info.title + ' - ' + info.database + ' - ' + info.folder+'migration/src',
		controls: [
			{ mode:'refresh'}
		]
	}
	return (
		<Page {...page}>
			{
				info.database && <SubmitForm {...config} ref={formRef} key={key}/>
			}
		</Page>
	)
}
export default Index